import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserPermissionRoutes } from '../api/permission'
import { routePermissionGuard, getUserPermissions, handlePermissionError } from '../utils/permission'
import HomeView from '../views/HomeView.vue'

// 静态路由配置
const staticRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/RBAC/Login.vue'),
  },
  {
    path: '/Main',
    name: 'Main',
    component: () => import('../views/MainView.vue'),
    meta: { requiresAuth: true },
    children: [
        

        ///物料群组
        {
          path: '/Item',
          name: 'Item',
          component: () => import('../views/MaterialManagement/ItemGroupView.vue'),
        },
        ///产品物料
        {
          path: '/Materials',
          name: 'Materials',
          component: () => import('../views/MaterialManagement/MaterialView.vue'),
        },
        //BOM
        {
          path: '/Bom',
          name: 'Bom',
          component: () => import('../views/MaterialManagement/BomView.vue'),
        },
        //  //看板
        {
          path: '/workbench',
          name: 'workbench',
          component: () => import('../views/MaterialManagement/WorkbenchView.vue'),
        },
        // 天气预报
        {
          path: '/weather',
          name: 'weather',
          component: () => import('../views/WeatherView.vue'),
        },
        // 智能客服
        {
          path: '/chat',
          name: 'chat',
          component: () => import('../views/ChatView.vue'),
        },
        // 车间
        {
          path: '/Work',
          name: 'Work',
          component: () => import('../views/Factory/WorkShow.vue'),
        },
        // 产线
        {
          path: '/Lienp',
          name: 'Lienp',
          component: () => import('../views/Factory/LienpShow.vue'),
        },
        // 工位
        {
          path: '/station',
          name: 'station',
          component: () => import('../views/Factory/StationShow.vue'),
        },

        //供应商
        {
          path: '/Supplier',
          name: 'Supplier',
          component: () => import('../views/SupplierCustom/SupplierView.vue'),
        },
        //客户
        {
          path: '/Custom',
          name: 'Custom',
          component: () => import('../views/SupplierCustom/CustomView.vue'),
        },
        //#region 工艺管理
        //工艺管理-->工序维护
        {
          path: '/ProcessStep',
          name: 'ProcessStep',
          component: () => import('../views/ProcessManagement/ProcessStepView.vue'),
        },
        //工艺管理-->工
        {
          path: '/Processrouting',
          name: 'Processrouting',
          component: () => import('../views/ProcessManagement/ProcessroutingView.vue'),
        },
        //#endregion 工艺管理
        //#region 生产管理
        //工单
        {
          path: '/ProductTable',
          name: 'ProductTable',
          component: () => import('../views/ProductionManagement/ProductTable.vue'),
        },
        //计划排程
        { 
          path: '/Project',
          name: 'Project',
          component: () => import('../views/ProductionManagement/ProjectSchedulingView.vue'),
        },
        //假期安排
        {
          path: '/LeaveManagement',
          name: 'LeaveManagement',
          component: () => import('../views/ProductionManagement/LeaveManagementView.vue'),
        },
        {
          path: '/CodingRule',
          name: 'CodingRule',
          component: () => import('../views/ProductionManagement/CodingRuleView.vue'),
        },
        //#endregion 生产管理
        // RBAC权限管理模块
        {
          path: '/UserManagement',
          name: 'UserManagement',
          component: () => import('../views/RBAC/UserManagement.vue'),
        },
        {
          path: '/RoleManagement',
          name: 'RoleManagement',
          component: () => import('../views/RBAC/RoleManagement.vue'),
        },
        {
          path: '/DepartmentManagement',
          name: 'DepartmentManagement',
          component: () => import('../views/RBAC/DepartmentManagement.vue'),
        },
        {
          path: '/PagePermissionManagement',
          name: 'PagePermissionManagement',
          component: () => import('../views/RBAC/PagePermissionManagement.vue'),
        },
        //订单
        {
          path: '/ERP',
          name: 'ERP',
          component: () => import('../views/ERP/ListView.vue'),
        },

        {
          path: '/defin',
          name: 'defin',
          component: () => import('../views/MaterialManagement/DefinView.vue'),
        },
        //#region 仓库+设备
        //仓库
        {
          path: '/storehouse',
          name: 'storehouse',
          component: () => import('../views/store/storehouse.vue'),
        },
        // 货架/库区
        {
          path: '/shelrShow',
          name: 'shelrShow',
          component: () => import('../views/store/shelrShow.vue'),
        },
        // 储位
        {
          path: '/storageShow',
          name: 'storageShow',
          component:()=>import('../views/store/storageShow.vue'),
        },
        // 材料库
        {
          path: '/WareMaterialShow',
          name: 'WareMaterialShow',
          component:()=>import('../views/store/WareMaterialShow.vue'),
        },
        // 成品库
        {
          path: '/finisedShow',
          name: 'finisedShow',
          component:()=>import('../views/store/finisedShow.vue'),
        },
        // 出入库记录
        {
          path: '/outininShow',
          name: 'outininShow',
          component:()=>import('../views/store/outininShow.vue'),
        },
         // 领料
        {
          path: '/Receive',
          name: 'Receive',
          component:()=>import('../views/store/Receive.vue'),
        },
        
        //#endregion

        // #region  质量检测
        //检测类型
        {
          path: '/testtype',
          name: 'testtype',
          component: () => import('../views/Quality/TestTypeView.vue'),
        },
        //检测项目
        {
          path: '/testproject',
          name: 'testproject',
          component: () => import('../views/Quality/TestProjectView.vue'),
        },
        //检测方案
         {
          path: '/testscheme',
          name: 'testscheme',
          component: () => import('../views/Quality/TestSchemeView.vue'),
        },
        //检测任务
         {
          path: '/testtask',
          name: 'testtask',
          component: () => import('../views/Quality/TestTaskView.vue'),
        },
        //原料检验
        {
          path: '/testincoming',
          name: 'testincoming',
          component: () => import('../views/Quality/TestIncomingView.vue'),
        },
        //成品检验
         {
          path: '/testfinish',
          name: 'testfinish',
          component: () => import('../views/Quality/TestFinishIncomingView.vue'),
        },
        //#endregion
        //设计审批
        {
          path: '/logic',
          name: 'logic',
          component: () => import('../views/logicflow/logicflowCustom.vue'),
        },
         //我的待办
        {
          path: '/audit',
          name: 'audit',
          component: () => import('../views/MaterialManagement/AuditView.vue'),
        },
        //设备类型
         {
          path: '/facility',
          name: 'facility',
          component: () => import('../views/Facility/FacilityView.vue'),
        },
        // 照片质量检测
        {
          path: '/photo-quality',
          name: 'PhotoQuality',
          component: () => import('../views/PhotoQualityView.vue'),
        },
         {
          path: '/pro',
          name: 'pro',
          component: () => import('../views/ProductionDashboard.vue'),
        },
      ]
    },
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoutes,
})

// 动态路由存储
let dynamicRoutesAdded = false

// 路由映射表 - 用于动态路由组件映射
const routeComponentMap: Record<string, () => Promise<any>> = {
  // 物料管理
  '/Item': () => import('../views/MaterialManagement/ItemGroupView.vue'),
  '/Materials': () => import('../views/MaterialManagement/MaterialView.vue'),
  '/Bom': () => import('../views/MaterialManagement/BomView.vue'),
  '/workbench': () => import('../views/MaterialManagement/WorkbenchView.vue'),
  '/defin': () => import('../views/MaterialManagement/DefinView.vue'),
  '/audit': () => import('../views/MaterialManagement/AuditView.vue'),
  
  // 工厂建模
  '/Work': () => import('../views/Factory/WorkShow.vue'),
  '/Lienp': () => import('../views/Factory/LienpShow.vue'),
  '/station': () => import('../views/Factory/StationShow.vue'),
  
  // 供应商客户
  '/Supplier': () => import('../views/SupplierCustom/SupplierView.vue'),
  '/Custom': () => import('../views/SupplierCustom/CustomView.vue'),
  
  // 工艺管理
  '/ProcessStep': () => import('../views/ProcessManagement/ProcessStepView.vue'),
  '/Processrouting': () => import('../views/ProcessManagement/ProcessroutingView.vue'),
  
  // 生产管理
  '/ProductTable': () => import('../views/ProductionManagement/ProductTable.vue'),
  '/Project': () => import('../views/ProductionManagement/ProjectSchedulingView.vue'),
  '/LeaveManagement': () => import('../views/ProductionManagement/LeaveManagementView.vue'),
  '/CodingRule': () => import('../views/ProductionManagement/CodingRuleView.vue'),
  
  // RBAC权限管理
  '/UserManagement': () => import('../views/RBAC/UserManagement.vue'),
  '/RoleManagement': () => import('../views/RBAC/RoleManagement.vue'),
  '/DepartmentManagement': () => import('../views/RBAC/DepartmentManagement.vue'),
  '/PagePermissionManagement': () => import('../views/RBAC/PagePermissionManagement.vue'),
  
  // ERP
  '/ERP': () => import('../views/ERP/ListView.vue'),
  
  // 仓库管理
  '/storehouse': () => import('../views/store/storehouse.vue'),
  '/shelrShow': () => import('../views/store/shelrShow.vue'),
  '/storageShow': () => import('../views/store/storageShow.vue'),
  '/WareMaterialShow': () => import('../views/store/WareMaterialShow.vue'),
  '/finisedShow': () => import('../views/store/finisedShow.vue'),
  '/outininShow': () => import('../views/store/outininShow.vue'),
  '/Receive': () => import('../views/store/Receive.vue'),
  
  // 质量检测
  '/testtype': () => import('../views/Quality/TestTypeView.vue'),
  '/testproject': () => import('../views/Quality/TestProjectView.vue'),
  '/testscheme': () => import('../views/Quality/TestSchemeView.vue'),
  '/testtask': () => import('../views/Quality/TestTaskView.vue'),
  '/testincoming': () => import('../views/Quality/TestIncomingView.vue'),
  '/testfinish': () => import('../views/Quality/TestFinishIncomingView.vue'),
  
  // 其他功能
  '/logic': () => import('../views/logicflow/logicflowCustom.vue'),
  '/facility': () => import('../views/Facility/FacilityView.vue'),
  '/photo-quality': () => import('../views/PhotoQualityView.vue'),
  '/pro': () => import('../views/ProductionDashboard.vue'),
  '/weather': () => import('../views/WeatherView.vue'),
  '/chat': () => import('../views/ChatView.vue'),
}

/**
 * 添加动态路由
 * @param routes 动态路由配置
 */
const addDynamicRoutes = (routes: any[]) => {
  if (dynamicRoutesAdded) return
  
  routes.forEach(route => {
    const routeConfig: RouteRecordRaw = {
      path: route.PermissionPath || route.path,
      name: route.PermissionCode || route.name,
      component: routeComponentMap[route.PermissionPath || route.path] || (() => import('../views/HomeView.vue')),
      meta: {
        title: route.PermissionName || route.title,
        icon: route.Icon || route.icon,
        requiresAuth: true,
        permission: route.PermissionCode || route.permission,
        permissionType: route.PermissionType || route.type,
        level: route.Level || route.level,
        sortOrder: route.SortOrder || route.sortOrder,
        status: route.Status || route.status
      }
    }
    
    // 添加到Main路由的children中
    const mainRoute = router.getRoutes().find(r => r.name === 'Main')
    if (mainRoute) {
      mainRoute.children?.push(routeConfig)
    }
  })
  
  dynamicRoutesAdded = true
}

/**
 * 检查用户是否有权限访问路由
 * @param route 路由信息
 * @param userPermissions 用户权限列表
 */
const hasPermission = (route: any, userPermissions: string[]): boolean => {
  if (!route.meta?.permission) return true
  return userPermissions.includes(route.meta.permission)
}

// 导航守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果访问登录页，直接放行
  if (to.name === 'Login') {
    next()
    return
  }
  
  // 检查是否需要认证
  if (to.meta?.requiresAuth) {
    if (!token) {
      ElMessage.warning('请先登录')
      next({ name: 'Login' })
      return
    }
    
    // 如果动态路由还未添加，则获取用户权限路由
    if (!dynamicRoutesAdded) {
      try {
        const response = await getUserPermissionRoutes()
        if (response.data.code === 200) {
          addDynamicRoutes(response.data.data)
          // 重新导航到目标路由
          next({ ...to, replace: true })
          return
        }
      } catch (error: any) {
        console.error('获取用户权限路由失败:', error)
        handlePermissionError(error)
        next({ name: 'Login' })
        return
      }
    }
    
            // 权限验证（只在动态路由已添加时进行）
            if (dynamicRoutesAdded) {
              try {
                const userPermissions = await getUserPermissions()
                const hasPermission = await routePermissionGuard(to, from, userPermissions)

                if (!hasPermission) {
                  // 如果没有权限，重定向到首页或登录页
                  next({ name: 'Login' })
                  return
                }
              } catch (error: any) {
                console.error('权限验证异常:', error)
                handlePermissionError(error)
                next({ name: 'Login' })
                return
              }
            }
  }
  
  next()
})

export default router
